import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import store from '@/store'
import { Message } from 'element-ui'

const state = {
  stompClient: null, // 全局唯一的 STOMP 客户端
  isConnected: false // 连接状态
}

const mutations = {
  SET_STOMP_CLIENT(state, client) {
    state.stompClient = client
  },
  SET_CONNECTION_STATUS(state, status) {
    state.isConnected = status
  }
}

const actions = {
  // 初始化全局 WebSocket 连接（仅执行一次）
  initWebSocket({ state, commit }) {
    return new Promise((resolve, reject) => {
      if (state.stompClient) {
        resolve(state.stompClient)
        return
      }

      const baseUrl = process.env.VUE_APP_BASE_API
      const socket = new SockJS(baseUrl + '/ws')
      const stompClient = Stomp.over(socket)
      commit('SET_STOMP_CLIENT', stompClient)

      stompClient.connect({
        'Authorization': store.getters.token
      }, () => {
        commit('SET_CONNECTION_STATUS', true)
        resolve(stompClient)
      }, (error) => {
        reject(error)
        commit('SET_CONNECTION_STATUS', false)
        console.error('连接断开，5秒后重连...')
        Message({
          message: '打开websocket异常：' + error.headers.message,
          type: 'error',
          duration: 5 * 1000
        })
        setTimeout(() => this.dispatch('initWebSocket'), 5000)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
